const express = require("express")
const router = express.Router()
const Cate = require("../controllers/cateController")
const cateObj = new Cate()
const Article = require("../controllers/articleController")
const articleObj = new Article()
const Jwt = require("../common/jwt")

router.get('/detail', async (req, res) => {
    let id = req.query.id || 1;
    await cateObj.detail(id).then(
        result => {
            res.send({
                result,
                msg: "根据id查询导航记录",
                code: 200
            })
        },
        err => {
            res.send({
                err,
                msg: "获取导航数据失败",
                code: -1
            })
        }
    )
})

router.get('/list', async (req, res) => {
    await cateObj.list().then(
        result => {
            res.send({
                result,
                msg: "查询导航所有记录",
                code: 200
            })
        },
        err => {
            res.send({
                err,
                msg: "获取导航数据失败",
                code: -1
            })
        }
    )



})
router.get('/search', async (req, res) => {
    let keyword = req.query.keyword;
    await cateObj.search(keyword).then(
        result => {
            res.send({
                result,
                msg: "根据关键字查询导航记录",
            })
        },
        err => {
            res.send({
                err,
                msg: "获取导航数据失败",
                code: -1
            })
        }
    )

})

router.get('/add', async (req, res) => {
    let { cate, cate_name, cate_url } = req.query;
    if (cate == undefined || cate_name == undefined) {
        res.send({
            code: -1,
            msg: "缺少参数",
        })
    }
    else {
        await cateObj.add(cate, cate_name, cate_url).then(
            result => {
                res.send({
                    result,
                    code: 200,
                    msg: "添加导航记录",
                })
            },
            err => {
                res.send({
                    err,
                    msg: "获取导航数据失败",
                    code: -1
                })
            }
        )

    }
})

router.post('/addBatch', async (req, res) => {
    let token = req.headers.token || req.headers['token'] || req.body.token;
    let { parentCate, childCates } = req.body;

    console.log('=== addBatch 请求调试信息 ===');
    console.log('Headers:', JSON.stringify(req.headers, null, 2));
    console.log('Token from headers:', req.headers.token);
    console.log('Body:', JSON.stringify(req.body, null, 2));
    console.log('Token value:', token);
    if (!token || token === 'undefined' || token === 'null' || token === null || token === undefined) {
        console.log('Token验证失败: token为空');
        res.status(401).json({
            code: -1,
            msg: "缺少token，请先登录"
        })
        return
    }

    if (!parentCate || (typeof parentCate === 'string' && parentCate.trim() === '') || !childCates || !Array.isArray(childCates) || childCates.length === 0) {
        console.log('参数验证失败');
        res.status(400).json({
            code: -1,
            msg: "缺少参数或参数格式不正确"
        })
        return
    }

    if (childCates.length > 3) {
        res.status(400).json({
            code: -1,
            msg: "二级导航最多只能添加3个"
        })
        return
    }

    let result = new Jwt(token).verifyToken();
    console.log('Token验证结果:', result);

    if (result.code == 200) {
        await cateObj.addBatch(parentCate.trim(), childCates).then(
            result => {
                res.status(200).json(result)
            },
            err => {
                console.error('添加分类失败:', err);
                res.status(500).json(err)
            }
        )
    } else {
        console.log('Token验证失败:', result.msg);
        res.status(401).json({
            code: -1,
            msg: result.msg || "您尚未登录或token无效，请重新登录"
        })
    }
})

router.get('/modify', async (req, res) => {
    let { cate, cate_name, cate_url, id } = req.query;
    if (cate == undefined || cate_name == undefined || id == undefined) {
        res.send({
            code: -1,
            msg: "缺少参数",
        })
    }
    else {
        await cateObj.modify(cate, cate_name, cate_url, id).then(
            result => {
                res.send({
                    result,
                    code: 200,
                    msg: "根据id修改导航记录",
                })
            },
            err => {
                res.send({
                    err,
                    msg: "获取导航数据失败",
                    code: -1
                })
            }
        )


    }
})

router.get('/remove', async (req, res) => {
    let { id } = req.query;
    if (id == undefined) {
        res.send({
            code: -1,
            msg: "缺少参数",
        })
    }
    else {
        await cateObj.remove(id).then(
            result => {
                res.send({
                    result,
                    code: 200,
                    msg: "根据id删除导航记录",
                })
            },
            err => {
                res.send({
                    err,
                    msg: "获取导航数据失败",
                    code: -1
                })
            }
        )

    }
})

router.post('/removeByParentCate', async (req, res) => {
    let token = req.headers.token || req.headers['token'] || req.body.token;
    let { parentCate } = req.body;

    if (!token || token === 'undefined' || token === 'null' || token === null || token === undefined) {
        res.status(401).json({
            code: -1,
            msg: "缺少token，请先登录"
        })
        return
    }

    if (!parentCate || (typeof parentCate === 'string' && parentCate.trim() === '')) {
        res.status(400).json({
            code: -1,
            msg: "缺少参数parentCate"
        })
        return
    }

    let jwtResult = new Jwt(token).verifyToken();

    if (jwtResult.code == 200) {
        try {
            await articleObj.updateArticlesByCate(parentCate.trim());
            await cateObj.removeByParentCate(parentCate.trim()).then(
                result => {
                    res.status(200).json({
                        code: 200,
                        msg: "删除分类成功，相关文章已更新为'暂无分类'",
                        result: result
                    })
                },
                err => {
                    console.error('删除分类失败:', err);
                    res.status(500).json({
                        code: -1,
                        msg: "删除分类失败",
                        err: err
                    })
                }
            )
        } catch (err) {
            console.error('删除分类过程出错:', err);
            res.status(500).json({
                code: -1,
                msg: "删除分类失败",
                err: err
            })
        }
    } else {
        res.status(401).json({
            code: -1,
            msg: jwtResult.msg || "您尚未登录或token无效，请重新登录"
        })
    }
})

router.get('/items', async (req, res) => {
    let { page_num, page_size } = req.query;
    if (page_num == undefined || page_size == undefined) {
        res.send({
            code: -1,
            msg: "缺少参数",
        })
    }
    else {
        let page_num2 = parseInt(page_num)
        let page_size2 = parseInt(page_size)
        await cateObj.items(page_num2, page_size2).then(
            result => {
                res.send({
                    result,
                    code: 200,
                    msg: "获取导航分页数据",
                })
            },
            err => {
                res.send({
                    err,
                    msg: "获取导航数据失败",
                    code: -1
                })
            }
        )
    }
})

module.exports = router;